package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.DynamicProblem;

import java.util.HashMap;
import java.util.Map;

/**
 * https://leetcode.com/problems/house-robber-iii/
 * see 198 213 337
 * <p>
 * 这个写法好像是  Recursion with Memoization, 不太是DP
 *
 * @author tzp
 * @since 2020/9/15
 */
public class LC337 implements DynamicProblem {
    public int rob(TreeNode root) {
        if (root == null) return 0;

        Map<TreeNode, Map<Boolean, Integer>> cache = new HashMap<>();
        int a = re(root, true, cache);
        int b = re(root, false, cache);
        return Math.max(a, b);
    }

    public int re(TreeNode root, boolean robRoot, Map<TreeNode, Map<Boolean, Integer>> cache) {
        if (cache.get(root) != null && cache.get(root).get(robRoot) != null) {
            return cache.get(root).get(robRoot);
        }
        int sum = 0;
        if (robRoot) {
            sum += root.val;
            if (root.left != null) {
                sum += re(root.left, false, cache);
            }
            if (root.right != null) {
                sum += re(root.right, false, cache);
            }
        } else {
            if (root.left != null) {
                int a = re(root.left, true, cache);
                int b = re(root.left, false, cache);
                int max = Math.max(a, b);
                sum += max;
            }
            if (root.right != null) {
                int a = re(root.right, true, cache);
                int b = re(root.right, false, cache);
                int max = Math.max(a, b);
                sum += max;
            }
        }

        cache.computeIfAbsent(root, k -> new HashMap<>());
        cache.get(root).put(robRoot, sum);
        return sum;
    }

    public static void main(String[] args) {
//        Integer[] a = new Integer[] {3,2,3,null,3,null,1};
        Integer[] a = new Integer[]{3, 4, 5, 1, 3, null, 1};
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        System.out.println(new LC337().rob(treeNode));
    }
}
